package com.echo.register.hosp.receiver;

import com.alibaba.fastjson.JSONObject;
import com.echo.register.common.constant.MqConst;
import com.echo.register.common.service.RabbitService;
import com.echo.register.hosp.service.ScheduleService;
import com.echo.register.model.hosp.Schedule;
import com.echo.register.vo.msm.MsmVo;
import com.echo.register.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: HospitalReceiver
 * @Package: com.echo.register.hosp.receiver
 * @Description: 消息消费者
 * @Author 谢同学
 * @Create 2024/1/6 17:40
 * @Version 1.0
 */
@Component
@Slf4j
public class HospitalReceiver {
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private RabbitService rabbitService;
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(MqConst.EXCHANGE_DIRECT_ORDER),// 交换机
            value = @Queue(name = MqConst.QUEUE_ORDER, durable = "true"),// 队列
            key = MqConst.ROUTING_ORDER) //key
            ) // 消费消息
    public void receive(Message message, Channel channel, OrderMqVo orderMqVo) {
        log.info("【医院服务-消费更新号源消息】：{}", JSONObject.toJSONString(orderMqVo));
        String scheduleId = orderMqVo.getScheduleId();
        Integer availableNumber = orderMqVo.getAvailableNumber();
        Integer reservedNumber = orderMqVo.getReservedNumber();
        // 查询原始数据
        Schedule schedule = scheduleService.getById(scheduleId);
        if (schedule != null) {
            schedule.setAvailableNumber(availableNumber);
            schedule.setReservedNumber(reservedNumber);
            // 更新数据
            scheduleService.updateSchedule(schedule);

            // 发送消息，由短信服务消费
            MsmVo msmVo = orderMqVo.getMsmVo();
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);
            log.info("【医院服务-发送通知消息】：{}", JSONObject.toJSONString(msmVo));
        }
    }
}
